<template>
  <div id="category">
    <category-header></category-header>
    <div class="category">
      <div class="left">
        <van-sidebar v-model="activeKey" class="sidebar">
          <van-sidebar-item
            v-for="(item, index) in categoryList"
            :key="index"
            :title="item.name"
            @click="itemClick(item.id)"
          />
        </van-sidebar>
      </div>
      <scroll class="content" ref="scroll">
        <router-view></router-view>
      </scroll>
    </div>
  </div>
</template>
<script>
import CategoryHeader from "components/category/CategoryHeader.vue";
import Scroll from "components/common/Scroll.vue";

import { getCategoryList } from "network/category";
export default {
  name: "Category",
  components: {
    CategoryHeader,
    Scroll,
  },
  data() {
    return {
      activeKey: 0,
      categoryList: [],
    };
  },
  created() {
    getCategoryList()
      .then((res) => {
        this.categoryList = res.data.data.categoryList;
      })
      .catch((err) => {
        console.log(err);
      });
    var timeInterval = setInterval(() => {
      if (this.categoryList.length > 0) {
        clearInterval(timeInterval);
        this.keepActive();
      }
    }, 50);
  },
  mounted() {
    const refresh = this.debounce(this.$refs.scroll.refresh,50)

    this.$bus.$on("itemImageLoad", () => {
      refresh()
    });
  },
  methods: {
    itemClick(id) {
      this.$router.push("/category/list/" + id);
    },
    keepActive() {
      for (let i = 0; i < this.categoryList.length; i++) {
        // console.log('......');
        if (this.categoryList[i].id == this.$route.params.id) {
          this.activeKey = i;
          break;
        }
      }
    },
    debounce(func, delay) {
      let timer = null;
      return function (...args) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
          func.apply(this, args);
        }, delay);
      };
    },
  },
};
</script>
<style scoped>
#category {
  position: relative;
  height: 100vh;
  overflow: hidden;
}
.left {
  float: left;
  width: 81px;
  height: 623px;
  padding: 5px 0;
  border-right: 1px solid #d9d9d9;
}
.left .sidebar {
  text-align: center;
}
.content {
  position: absolute;
  left: 81px;
  right: 0;
  top: 44px;
  bottom: 50px;
}
</style>